package com.jushu.storbox.util.image;

import java.io.File;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import android.graphics.Bitmap;
import android.util.LogPrinter;

import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.util.LogUtil;
import com.huawei.sharedrive.sdk.android.util.StringUtil;

public abstract class AbsImageLoader {

	public enum LoadType {
		FILE_PATH_INVALIED, FILE_NOT_EXISTS, FILE_NOT_SUPPORT, MEMERY_NOT_SUPPORT, DECODE_IMAGE_FAILURE, DECODE_IMAGE_SUCCESS;
	}

//	private ExecutorService mImageThreadPool = Executors.newFixedThreadPool(3);
	private ExecutorService mImageThreadPool = new ThreadPoolExecutor(3, 3, 0L,
			TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1000));
	// private BlockingQueue<Runnable> queue = new
	// LinkedBlockingQueue<Runnable>();// new ArrayBlockingQueue<Runnable>(100);

	// private ThreadPoolExecutor mImageThreadPool = new ThreadPoolExecutor(5,
	// 10, 0l, TimeUnit.MILLISECONDS, queue);// , new
	// ThreadPoolExecutor.CallerRunsPolicy());

	public final void loadImage(final String imagePath) {
		mImageThreadPool.execute(new Runnable() {
			public void run() {
				if (StringUtil.isBlank(imagePath)) {
					onLoadFailure(imagePath, LoadType.FILE_PATH_INVALIED);
					return;
				}
				File file = new File(imagePath);
				if (!file.exists()) {
					onLoadFailure(imagePath, LoadType.FILE_NOT_EXISTS);
					return;
				}

				// if() {
				// onLoadFailure(imagePath, LoadType.FILE_NOT_SUPPORT);
				// return ;
				// }

				try {
					Bitmap mBitmap = BitmapUtil.createImageThumbnail(imagePath, ClientConfig.LOCAL_THUMBNAIL_WIDTH, ClientConfig.LOCAL_THUMBNAIL_WIDTH);
					if (mBitmap == null) {
						onLoadFailure(imagePath, LoadType.DECODE_IMAGE_FAILURE);
					} else {
						onLoadSuccess(mBitmap);
					}
				} catch (OutOfMemoryError e) {
					LogUtil.e("OutOfMemoryError", e.getMessage());
					onLoadFailure(imagePath, LoadType.MEMERY_NOT_SUPPORT);
				}
			}
		});
	}

	protected abstract void onLoadSuccess(Bitmap mBitmap);

	protected abstract void onLoadFailure(String imagePath, LoadType failureType);

}
